<template>
  <div class="dateRange">
    <el-date-picker
      ref="start"
      key="start"
      v-model="bindStart"
      placeholder="起始时间"
      v-bind="$attrs"
      :picker-options="{ disabledDate: disabledStartDate }"
      default-time="00:00:00"
      @change="onStartChange"
      @clear="onClear"
    />
    <el-date-picker
      ref="end"
      key="end"
      v-model="bindEnd"
      placeholder="结束时间"
      v-bind="$attrs"
      :picker-options="{ disabledDate: disabledEndDate }"
      default-time="23:59:59"
      @change="onEndChange"
      @clear="onClear"
    />
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  inheritAttrs: false,
  props: {
    start: String,
    end: String
  },
  data() {
    return {
      bindStart: '',
      bindEnd: ''
    }
  },
  watch: {
    start: {
      handler(val) {
        this.bindStart = val
      },
      immediate: true
    },
    end: {
      handler(val) {
        this.bindEnd = val
      },
      immediate: true
    }
  },
  methods: {
    /**
     * @param {Date} e
     */
    onStartChange(e) {
      this.$emit('update:start', e ? e.toString() : '')
      if (e !== null && !this.bindEnd) {
        this.$refs.end.focus()
      }
      this.emitChange(!e)
    },
    /**
     * @param {Date} e
     */
    onEndChange(e) {
      let end = e || ''
      if (e && this.bindStart && e < this.bindStart) {
        end = dayjs(this.bindStart)
          .hour(23)
          .minute(59)
          .second(59)
          .format('YYYY-MM-DD HH:mm:ss')
      }
      this.$emit('update:end', end.toString())
      this.emitChange(!e)
    },
    /**
     * @param {Date} time
     */
    disabledStartDate(time) {
      if (this.bindEnd) {
        return time > new Date(this.bindEnd)
      }
      return false
    },
    /**
     * @param {Date} time
     */
    disabledEndDate(time) {
      if (this.bindStart) {
        return time < new Date(this.bindStart)
      }
      return false
    },
    /**
     * @param {boolean} isClear
     */
    emitChange(isClear) {
      if (isClear) {
        return this.onClear()
      }
      if (this.bindStart && this.bindEnd) {
        this.$emit('pick')
      }
    },
    onClear() {
      this.$emit('update:start', '')
      this.$emit('update:end', '')
      this.$emit('pick')
    }
  }
}
</script>

<style scoped lang="scss">
.dateRange {
  display: flex;
  width: 300px;
}
</style>
